﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using CrmCustomInstallActions.CrmSdk;
using CrmCustomInstallActions.MetadataServiceSdk;
using CrmCustomInstallActions.CrmSdk.Discovery;

namespace CrmCustomInstallActions.UI
{
    public partial class CrmSolutionInstallerLoginForm : Form
    {
        private Helpers.CrmAuthentication crmAuth = null;
        OrganizationDetail[] orgs = null;
        public CrmSolutionInstallerLoginForm()
        {
            InitializeComponent();
            chkDefaultCredentials.Checked = true;
            SetCredentialsUI(true);

            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM", false);
                if (key != null)
                {
                    string url = Convert.ToString(key.GetValue("ServerUrl", "")).Replace("MSCRMServices", "");
                    crmAuth = new CrmCustomInstallActions.Helpers.CrmAuthentication(url);
                    try
                    {
                        orgs = crmAuth.GetOrganizations((ICredentials)System.Net.CredentialCache.DefaultNetworkCredentials, 0);
                        LoadOrgList(orgs);
                        btnOk.Focus();

                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception)
            {

            }

        }

        private void LoadOrgList(OrganizationDetail[] orgs)
        {
            cmbOrganizations.Items.Clear();
            foreach (OrganizationDetail org in orgs)
            {
                cmbOrganizations.Items.Add(org.OrganizationName);
            }
            cmbOrganizations.SelectedIndex = 0;
            btnOk.Enabled = true;
        }

        private System.Net.NetworkCredential _Credential = System.Net.CredentialCache.DefaultNetworkCredentials;

        public System.Net.NetworkCredential Credential
        {
            get { return _Credential; }
        }

        private void chkDefaultCredentials_CheckedChanged(object sender, EventArgs e)
        {
            SetCredentialsUI(chkDefaultCredentials.Checked);
            btnOk.Enabled = (cmbOrganizations.Items.Count > 0);
        }

        private void SetCredentialsUI(bool UseDefaultCredentials)
        {
            cmbOrganizations.Items.Clear();
            if (UseDefaultCredentials)
            {
                // 234; 243; 255
                txtUserName.BackColor = Color.FromArgb(234, 243, 255);
                txtUserName.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                txtUserName.ReadOnly = true;
                txtPassword.BackColor = txtUserName.BackColor;
                txtPassword.Text = "";
                txtPassword.ReadOnly = true;
                txtServerUrl_Leave(null, null);
            }
            else
            {
                txtUserName.BackColor = Color.White;
                txtUserName.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                txtUserName.ReadOnly = false;
                txtPassword.BackColor = Color.White;
                txtPassword.Text = "";
                txtPassword.ReadOnly = false;
                txtUserName.Focus();
            }
        }

        private void txtUserName_Leave(object sender, EventArgs e)
        {
            if (!txtUserName.ReadOnly && txtUserName.Text.IndexOf('\\') < 0)
            {
                MessageBox.Show("You must type your user name as DOMAIN\\LOGIN NAME", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                txtUserName.Focus();
            }
            else
            {
                if (txtPassword.Text.Length > 0)
                {
                    txtServerUrl_Leave(sender, e);
                }
            }
        }

        private void CrmSolutionInstallerLoginForm_Load(object sender, EventArgs e)
        {

        }

        private void txtServerUrl_Leave(object sender, EventArgs e)
        {
            if (txtServerUrl.Text.Length > 0 && cmbOrganizations.Items.Count == 0)
            {
                if (chkDefaultCredentials.Checked)
                {
                    try
                    {
                        crmAuth = new CrmCustomInstallActions.Helpers.CrmAuthentication(txtServerUrl.Text);
                        _Credential = System.Net.CredentialCache.DefaultNetworkCredentials;
                        orgs = crmAuth.GetOrganizations((ICredentials)_Credential, 0);
                        LoadOrgList(orgs);
                        btnOk.Focus();
                    }
                    catch (Exception)
                    {

                    }
                }
                else
                {
                    if (txtUserName.Text.Length > 0 && txtUserName.Text.IndexOf("\\") >= 0 && txtPassword.Text != "")
                    {
                        try
                        {
                            _Credential = new NetworkCredential(txtUserName.Text.Split('\\')[1], txtPassword.Text, txtUserName.Text.Split('\\')[0]);
                            orgs = crmAuth.GetOrganizations((ICredentials)_Credential, 0);
                            LoadOrgList(orgs);
                            btnOk.Focus();
                        }
                        catch (Exception)
                        {

                            // throw;
                        }


                    }
                }
            }
        }

        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            cmbOrganizations.Items.Clear();
            btnOk.Enabled = false;
        }

        private void txtPassword_Leave(object sender, EventArgs e)
        {
            txtServerUrl_Leave(sender, e);
        }

        private void txtUserName_TextChanged(object sender, EventArgs e)
        {
            cmbOrganizations.Items.Clear();
            btnOk.Enabled = false;
        }

        private void txtServerUrl_TextChanged(object sender, EventArgs e)
        {
            cmbOrganizations.Items.Clear();
            btnOk.Enabled = false;
        }


        private CrmService _CrmService;

        public CrmService CrmService
        {
            get { return _CrmService; }
        }

        private MetadataServiceSdk.MetadataService _MetadataService;

        public MetadataServiceSdk.MetadataService MetadataService
        {
            get { return _MetadataService; }
        }

        internal void Authenticate()
        {

            if (orgs == null)
            {
                _CrmService = null;
                _MetadataService = null;
                return;
            }

            OrganizationDetail org = orgs.FirstOrDefault(o => o.OrganizationName == Convert.ToString(cmbOrganizations.SelectedItem));
            if (org == null)
            {
                _CrmService = null;
                _MetadataService = null;
                return;
            }

            try
            {
                // Create CrmService Token
                CrmSdk.CrmAuthenticationToken token = new CrmSdk.CrmAuthenticationToken();
                token.AuthenticationType = 0;
                token.OrganizationName = org.OrganizationName;
                // Create CrmService
                _CrmService = new CrmService();
                _CrmService.Url = org.CrmServiceUrl;
                _CrmService.CrmAuthenticationTokenValue = token;
                _CrmService.Credentials = _Credential;
                _CrmService.PreAuthenticate = true;


                // Create Metadata Token

                MetadataServiceSdk.CrmAuthenticationToken token2 = new MetadataServiceSdk.CrmAuthenticationToken();
                token2.AuthenticationType = 0;
                token2.OrganizationName = org.OrganizationName;

                // Create Metadata Service
                _MetadataService = new MetadataService();
                _MetadataService.Url = org.CrmMetadataServiceUrl;
                _MetadataService.CrmAuthenticationTokenValue = token2;
                _MetadataService.Credentials = _Credential;
                _MetadataService.PreAuthenticate = true;

            }
            catch (Exception)
            {
                _CrmService = null;
                _MetadataService = null;
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Hide();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Authenticate();
            if (_CrmService == null)
            {
                MessageBox.Show("It was not possible to login to the CRM System using the current setting. Please correct and try again", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                this.Hide();
            }
        }






    }
}
